/*
 * 
 *	Copyright (C) 2011 -- Alfred Reibenschuh
 *
 * 	This program is free software; you can redistribute it and/or 
 *	modify it under the terms of the GNU General Public License as 
 *	published by the Free Software Foundation; either version 2 of 
 *	the License, or (at your option) any later version.
 *
 *	This program is distributed in the hope that it will be useful, 
 *	but WITHOUT ANY WARRANTY; without even the implied warranty of 
 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
 *	GNU General Public License for more details.
 * 
 */

package redoak.php.snmp;

import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.logging.Logger;

import com.caucho.quercus.annotation.Optional;
import com.caucho.quercus.env.Env;
import com.caucho.quercus.env.Value;
import com.caucho.util.L10N;

public class JoeSnmpModule extends AbstractSnmpModule 
{
	private static final Logger log = Logger.getLogger(JoeSnmpModule.class.getName());
	private static final L10N L = new L10N(JoeSnmpModule.class);
	
	public Value snmp_session(Env env, String hostname, String community, @Optional Integer timeout, @Optional Integer retries)
	{
		int port = 161;
		if(hostname.indexOf(':')>=1)
		{
			port = Integer.parseInt(hostname.substring(hostname.indexOf(':')+1));
			hostname = hostname.substring(0,hostname.indexOf(':'));
		}
		
		ISnmpModuleSession session = null;
		try 
		{
			session = JoeSnmpModuleSession.createV1(hostname, port, community);
			session.setRetries((retries==null) ? 3 : ((retries<1) ? 3 : retries));
			session.setTimeout((timeout==null) ? 100 : ((timeout<1) ? 100 : timeout));	
		} 
		catch (UnknownHostException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		catch (SocketException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return env.wrapJava(session, true);
	}

	public Value snmp2c_session(Env env, String hostname, String community, @Optional Integer timeout, @Optional Integer retries)
	{
		int port = 161;
		if(hostname.indexOf(':')>=1)
		{
			port = Integer.parseInt(hostname.substring(hostname.indexOf(':')+1));
			hostname = hostname.substring(0,hostname.indexOf(':'));
		}

		ISnmpModuleSession session = null;
		try 
		{
			session = JoeSnmpModuleSession.createV2(hostname, port, community);
			session.setRetries((retries==null) ? 3 : ((retries<1) ? 3 : retries));
			session.setTimeout((timeout==null) ? 100 : ((timeout<1) ? 100 : timeout));	
		} 
		catch (UnknownHostException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		catch (SocketException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return env.wrapJava(session, true);
	}

}
